package com.xiaoke.security.config;

import com.xiaoke.security.config.properties.SecurityProperties;
import com.xiaoke.security.handle.MyAuthenctiationFailureHandler;
import com.xiaoke.security.handle.MyAuthenticationSuccessHandler;
import com.xiaoke.security.verificationCode.ValidateCodeFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author 小柯
 * @Date 2019/11/2  17:53
 * 安全就是认证和授权
 *
 **/

@Configuration
@Slf4j
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    private MyAuthenctiationFailureHandler myAuthenctiationFailureHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }




    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(myAuthenctiationFailureHandler);
        validateCodeFilter.setSecurityProperties(securityProperties);
        validateCodeFilter.afterPropertiesSet();

        log.info("securityProperties.getBrowser().getLoginPage()" + securityProperties.getBrowser().getLoginPage());

        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()  //表单登录 ---  认证
                .loginPage(/*"/login-in.html"*/"/authentication/require") //要在下面授权中放行，否则会死循环
                .loginProcessingUrl("/authentication/from")
                .successHandler(myAuthenticationSuccessHandler) //表单登录成功时使用我们自己写的处理类
                .and()
                .authorizeRequests()  //对请求授权
                .antMatchers(/*"/login-in.html"*/"/authentication/require", securityProperties.getBrowser().getLoginPage(), "/code/image").permitAll() //1、登录页不需要认证，2、没有配置登陆成功跳转页，跳转回登录页也不需要认证。
                .anyRequest()   //任何请求
                .authenticated() //都需要身份认证
                .and().csrf().disable();

    }



}
